var express = require("express");
var router = express.Router();

// todo 引入jst，用于生成token
const jwt = require("jsonwebtoken");

// todo 引入node-rsa，用于生成密钥对
const NodeRSA = require("node-rsa");
const key = new NodeRSA({ b: 512 });
key.setOptions({ encryptionScheme: "pkcs1" });

const Users = require("../models/users");

// todo 预登录接口
router.get("/key", (req, res, next) => {
  // todo 生成公钥
  let publicKey = key.exportKey("public");
  console.log(publicKey);
  res.json({
    publicKey: publicKey,
  });
});

// todo 登录接口
router.post("/login", function (req, res, next) {
  // todo 拿到前端发来的密文
  const { info } = req.body;

  let decrypted = key.decrypt(info, "utf8"); //解密
  const { username, password } = JSON.parse(decrypted);

  // const { username, password } = req.body;
  if (!username || !password) {
    res.json({
      status: 1001,
      msg: "参数错误",
    });
  } else {
    // todo find找到的是数组,没找到返回[]
    // todo findOne找到的是对象,没找到返回的是null
    Users.findOne({ username }, (err, doc) => {
      if (err) throw err;
      if (doc) {
        if (password === doc.password) {
          // todo 需要在登录成功以后去生成token
          let payload = { username: username };
          // todo 签名做加密，解密
          let secret = "I_LOVE_JING";
          let token = jwt.sign(payload, secret, { expiresIn: 60 * 1 });
          // console.log(token)
          res.json({
            status: 0,
            msg: "登录成功",
            token: token,
          });
        } else {
          res.json({
            status: 1003,
            msg: "密码错误",
          });
        }
      } else {
        res.json({
          status: 1002,
          msg: "用户不存在",
        });
      }
    });
  }
});

module.exports = router;
